package servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.org.apache.bcel.internal.generic.NEW;

import dao.ArticleDAO;
import dao.CommentDAO;
import dao.SensitiveWordDAO;
import entity.Article;
import entity.Comment;
import entity.User;

/**
 * Servlet implementation class AddCommentServlet
 */
@WebServlet("/AddCommentServlet")
public class AddCommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private CommentDAO commentDAO = CommentDAO.getInstance();   
    private ArticleDAO articleDAO = ArticleDAO.getInstance();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCommentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try{
			int article_id=Integer.parseInt((String)request.getParameter("article_id"));
			String content = (String)request.getParameter("editorValue");
			SensitiveWordDAO sl = SensitiveWordDAO.getInstance();
			content = sl.Sensitive(content);
			//User user = new User(1, "111111", "请问长得太帅怎么办", 0,0, "619728921@qq.com","18092815820");
			HttpSession session = request.getSession();
			//session.setAttribute("user", user);
			User user = (User) session.getAttribute("user");
			if(user!=null){
				//User user =(User)((HttpSession)request.getSession()).getAttribute("user");
				System.out.println("这个用户是谁？"+user.getUser_name());
				Comment comment = new Comment(article_id,user.getUser_id(),content);
				commentDAO.add(comment);
			    Article article = articleDAO.get(article_id);
			    article.setArticle_comment_num(article.getArticle_comment_num()+1);
			    articleDAO.update(article);
				response.sendRedirect("ShowTieServlet?article_id="+article_id);
			}
			else{
				response.sendRedirect("UserLogin");//没登陆就让它去登陆
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
